package LocalServerProtocols;

import generalClasses.Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;


public class AuthenticateLocalServer extends localServerProtocol
{
	
	public AuthenticateLocalServer(Server serverDetails)
	{
		super();
		this._serverResponse = null;
		this._firstDesieredServerRespose = "SEND_LOCAL_SERVER";
		this._secondDesieredServerRespose = "SERVER_LOGIN_SUCCESSFUL";
		this._serverDetails = serverDetails;
		this._protocolAction = "LOCAL_SERVER_IDINTIFICATION";
		
	}
	@Override
	public String exec(ObjectOutputStream oos, PrintWriter out,
			BufferedReader in, ObjectInputStream ois,String action)
	{
		
		String result = new String("Fail");
		//write command to Main Server
		out.flush();
		out.println(action);
		System.out.println("I sent to Main Server "+action);
		
		//Try to read server response
		try
		{
			this._serverResponse = in.readLine();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.getMessage());
			System.out.println("Couldn't read server response");
			return result;
		}
		
		if (_serverResponse != null)
		{
			if (_serverResponse.contains(_firstDesieredServerRespose))
			{
				System.out.println("I got "+_serverResponse+" from server");
				

				//Sending Details to server
				try
				{
					oos.writeObject(_serverDetails);
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println(e.getMessage());
					System.out.println("Couldn't send server object to Main Server");
					return result;
				}
				
				//try to read Main Server Response for Authentication
				try
				{
					_serverResponse = in.readLine();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println(e.getMessage());
					System.out.println("Couldn't read server response to Authentication");
					return result;
				}
				if ( _serverResponse.equalsIgnoreCase(_secondDesieredServerRespose) )
				{
					result = "Succcess";
					return result;
				}
				else
				{
					System.out.println("Error !! server respond was: "+_serverResponse +" and not "+_secondDesieredServerRespose);
					return result;
				}
				
			}
		}
		else
		{
			System.out.println("The Server send me null");
		}
		return null;
	}

}
